package de.gis;

import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.json.JSONArray;
import org.json.JSONObject;

import android.content.SharedPreferences;
import android.util.Log;
import de.gis.ImageLocator.replication_direction;

public class Replicator extends CouchCommunicator {
	private final replication_direction direction;

	public Replicator(String dbUrl, String remoteUrl,
			replication_direction direction, SharedPreferences prefs) {
		super(dbUrl, prefs);
		this.remoteUrl = remoteUrl;
		this.direction = direction;
		//initialize(prefs);
	}

	@Override
	public void initialize(SharedPreferences prefs) {
		// dangerous: called from super's constructor
		super.initialize(prefs);
		remoteCredentials = prefs.getString(remoteUrl, null);
	}

	private static final String TAG = "Uploader";
	private String remoteUrl;
	private String remoteCredentials;

	public void doit() throws Exception {
		Log.d(TAG, "Replicate");
		if (remoteCredentials == null) {
			// how can we find out if the remote host needs authentication?
			// unfortunately the local host does not return a 403
			Log.d(TAG, "Need credentials for replication");
			throw new UnauthorizedException(false /* isLocal */);
		}
		HttpPost request = createHttpPost(dbUrl + "_replicate");
		String source;
		String target;
		if (direction == replication_direction.TO_LOCAL) {
			source = remoteUrl + ImageLocator.DATABASE;
			target = ImageLocator.DATABASE;
		} else {
			source = ImageLocator.DATABASE;
			target = remoteUrl + ImageLocator.DATABASE;
			if (remoteCredentials != null) {
				target = target.replace("http://", "http://" + remoteCredentials + "@");
			}
		}
		String requestData = "{ \"source\":\"" + source + "\",\"target\":\""
				+ target + "\"}";
		addJson(request, requestData);
		Log.d(TAG, "Replicating-request: " + requestData);
		JSONObject response = getResponse(request);
		Log.d(TAG, "Replication-response: " + response.toString(2));
		if (response.has("history")) {
			JSONArray history = response.getJSONArray("history");
			if (history.length() >= 0) {
				JSONObject result = history.getJSONObject(0);
				if (result != null) {
					int write_failures = result.getInt("doc_write_failures");
					if (write_failures > 0) {
						throw new UnauthorizedException(false /* isLocal */);
					}
				}
			}
		}
		
		Log.d(TAG, "Replication successful");

	}
}
